import React, { useState, useEffect } from 'react';
import { userAPI, activityAPI } from '../../services/api';
import LoadingSpinner from '../../components/common/LoadingSpinner';
import { FiUsers, FiActivity, FiUser, FiBarChart2 } from 'react-icons/fi';

const Dashboard = () => {
  const [stats, setStats] = useState({
    totalUsers: 0,
    totalActivities: 0,
    onlineUsers: 0,
    adminUsers: 0
  });
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    const fetchStats = async () => {
      try {
        // 分别获取各项统计数据，使用Promise.all处理并行请求
        const [userResponse, activityResponse, onlineResponse, adminResponse] = await Promise.all([
          // 获取用户统计数据
          userAPI.getUsers({ limit: 1 }),
          // 获取活动统计数据
          activityAPI.getActivities({ limit: 1 }),
          // 获取在线用户，使用try-catch处理单独可能失败的请求
          (async () => {
            try {
              // 修改：不使用固定limit=1000，而是使用分页参数
              return await userAPI.getUsers({ 
                page: 1,
                limit: 10,
                status: 'online' 
              });
            } catch (error) {
              console.error('获取在线用户失败:', error);
              // 返回默认值，避免整个统计失败
              return { data: { data: { pagination: { totalUsers: 0 } } } };
            }
          })(),
          // 获取管理员用户，使用try-catch处理单独可能失败的请求
          (async () => {
            try {
              // 修改：不使用固定limit=1000，而是使用分页参数
              return await userAPI.getUsers({ 
                page: 1,
                limit: 10,
                role: 'admin' 
              });
            } catch (error) {
              console.error('获取管理员用户失败:', error);
              // 返回默认值，避免整个统计失败
              return { data: { data: { pagination: { totalUsers: 0 } } } };
            }
          })()
        ]);
        
        setStats({
          totalUsers: userResponse?.data?.data?.pagination?.totalUsers || 0,
          totalActivities: activityResponse?.data?.data?.pagination?.totalActivities || 0,
          onlineUsers: onlineResponse?.data?.data?.pagination?.totalUsers || 0,
          adminUsers: adminResponse?.data?.data?.pagination?.totalUsers || 0
        });
        
        // 清除错误状态
        setError(null);
      } catch (err) {
        console.error('获取统计数据错误:', err);
        // 即使发生错误，也设置loading为false，允许页面继续渲染
        // 可以根据需要显示部分统计数据
      } finally {
        setLoading(false);
      }
    };

    fetchStats();
  }, []);

  const statCards = [
    {
      title: '总用户数',
      value: stats.totalUsers,
      icon: <FiUsers className="h-6 w-6 text-blue-500" />,
      color: 'bg-blue-100'
    },
    {
      title: '活动总数',
      value: stats.totalActivities,
      icon: <FiActivity className="h-6 w-6 text-green-500" />,
      color: 'bg-green-100'
    },
    {
      title: '在线用户',
      value: stats.onlineUsers,
      icon: <FiUser className="h-6 w-6 text-yellow-500" />,
      color: 'bg-yellow-100'
    },
    {
      title: '管理员数',
      value: stats.adminUsers,
      icon: <FiBarChart2 className="h-6 w-6 text-purple-500" />,
      color: 'bg-purple-100'
    }
  ];

  if (loading) {
    return (
      <div className="flex justify-center items-center h-64">
        <LoadingSpinner />
      </div>
    );
  }

  if (error) {
    return (
      <div className="bg-red-50 border-l-4 border-red-400 p-4">
        <div className="flex">
          <div className="flex-shrink-0">
            <svg className="h-5 w-5 text-red-400" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor">
              <path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z" clipRule="evenodd" />
            </svg>
          </div>
          <div className="ml-3">
            <p className="text-sm text-red-700">
              {error}
            </p>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="py-6">
      <div className="max-w-7xl mx-auto px-4 sm:px-6 md:px-8">
        <h1 className="text-2xl font-semibold text-gray-900">仪表板</h1>
      </div>
      
      <div className="max-w-7xl mx-auto px-4 sm:px-6 md:px-8">
        {/* 统计卡片 */}
        <div className="mt-6 grid grid-cols-1 gap-5 sm:grid-cols-2 lg:grid-cols-4">
          {statCards.map((card, index) => (
            <div key={index} className="bg-white overflow-hidden shadow rounded-lg">
              <div className="p-5">
                <div className="flex items-center">
                  <div className={`flex-shrink-0 rounded-md p-3 ${card.color}`}>
                    {card.icon}
                  </div>
                  <div className="ml-5 w-0 flex-1">
                    <dl>
                      <dt className="text-sm font-medium text-gray-500 truncate">
                        {card.title}
                      </dt>
                      <dd className="flex items-baseline">
                        <div className="text-2xl font-semibold text-gray-900">
                          {card.value}
                        </div>
                      </dd>
                    </dl>
                  </div>
                </div>
              </div>
            </div>
          ))}
        </div>

        {/* 最近活动 */}
        <div className="mt-8">
          <div className="bg-white shadow overflow-hidden sm:rounded-lg">
            <div className="px-4 py-5 sm:px-6">
              <h3 className="text-lg leading-6 font-medium text-gray-900">
                系统概览
              </h3>
              <p className="mt-1 max-w-2xl text-sm text-gray-500">
                活动组织系统的使用情况
              </p>
            </div>
            <div className="border-t border-gray-200">
              <dl>
                <div className="bg-gray-50 px-4 py-5 sm:grid sm:grid-cols-3 sm:gap-4 sm:px-6">
                  <dt className="text-sm font-medium text-gray-500">
                    系统版本
                  </dt>
                  <dd className="mt-1 text-sm text-gray-900 sm:mt-0 sm:col-span-2">
                    v1.0.0
                  </dd>
                </div>
                <div className="bg-white px-4 py-5 sm:grid sm:grid-cols-3 sm:gap-4 sm:px-6">
                  <dt className="text-sm font-medium text-gray-500">
                    技术栈
                  </dt>
                  <dd className="mt-1 text-sm text-gray-900 sm:mt-0 sm:col-span-2">
                    React, Node.js, MongoDB
                  </dd>
                </div>
                <div className="bg-gray-50 px-4 py-5 sm:grid sm:grid-cols-3 sm:gap-4 sm:px-6">
                  <dt className="text-sm font-medium text-gray-500">
                    支持
                  </dt>
                  <dd className="mt-1 text-sm text-gray-900 sm:mt-0 sm:col-span-2">
                    support@activity-system.com
                  </dd>
                </div>
              </dl>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default Dashboard;